package com.apes.framework.util.monitor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.plugin.cache.Cache;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能：监控管理器
 *
 * @author xul
 * @create 2020-07-16 15:07
 */

@Service
public class MonitorManager {
    private StringRedisTemplate template;
    private Cache cache;

    public MonitorManager(Cache cache, StringRedisTemplate template) {
        this.cache = cache;
        this.template = template;
    }

    public Map setting(SimpleRequest request) {
        JSONObject jo = JSON.parseObject((String) request.getData());
        Map<String, Boolean> settings = new HashMap<>();
        for (String k : jo.keySet()) {
            Boolean v = jo.getBoolean(k);
            settings.put(k, v);
        }
        cache.put(Constants.MONITOR_SETTING_TOPIC, settings);
        template.convertAndSend(Constants.MONITOR_SETTING_TOPIC, request.getData());
        return (Map<String, Boolean>) cache.get(Constants.MONITOR_SETTING_TOPIC);
    }

    public Map view() {
        Map<String, Boolean> settings = (Map<String, Boolean>) this.cache.get(Constants.MONITOR_SETTING_TOPIC);
        if (settings == null) {
            settings = new HashMap<>();
        }
        return settings;
    }

}
